const router = require('koa-router')();

router.prefix('/api/log', '日志相关接口');

router.post('/:level', async (ctx) => {
  let level = (ctx.params.level || 'debug').toLowerCase();
  let message = (ctx.request.body || {}).message;

  let func = ctx.logger.debug;

  if (level == 'error') {
    func = ctx.logger.error;
  } else if (level == 'info') {
    func = ctx.logger.info;
  }

  ctx.body = await func.bind(ctx.logger)(message);
}, {
  desc: '记录日志信息',
  level: '日志级别(debug、info、error)',
  body: {
    message: { type: 'string', desc: '日志信息' }
  }
});

router.post('/logs/search', async (ctx) => {
  let json = ctx.request.body || {};

  let so = {
    pageIndex: json.pageIndex || 1,
    pageSize: json.pageSize || 20,
    filters: []
  };

  if (json.level) {
    so.filters.push({ field: 'LogLevel', op: '=', value: json.level });
  }

  if (json.keywords) {
    so.filters.push({ field: 'Message', op: 'like', value: json.keywords });
  }

  ctx.body = await ctx.logger.search(so);
}, {
  desc: '查询日志信息',
  body: {
    pageIndex: { type: 'integer', desc: '页序号' },
    pageSize: { type: 'integer', desc: '每页显示数据大小' },
    level: { type: 'string', desc: '日志级别' },
    keywords: { type: 'string', desc: '消息关键字' }
  }
});

router.delete('/clear', async (ctx) => {
  ctx.body = await ctx.logger.clear();
}, '清空日志信息');

module.exports = router;